<template>
  <div class="edit-wrap">
    <div class="tree-before-wrap">
      <el-input v-if="isAdding" v-model="nameOfNewNode" placeholder="请输入节点名称" style="margin-right: 8px"></el-input>
      <template v-else-if="currentNode">
        <el-input v-model="currentNode.meta.title" style="margin-right: 8px">
          <i slot="prepend" style="color: #3a71a8" class="el-icon-aim"> 当前节点</i>
        </el-input>
      </template>
      <x2-space />
      <x2-space width="10px" />
      <el-button @click="handleAddNodeBtn" type="primary">{{ isAdding ? '确定' : '新增节点' }}</el-button>
      <el-button v-if="isAdding" @click="isAdding = false" type="danger">取消</el-button>
    </div>
    <div class="tree-wrap">
      <el-tree
        ref="TR"
        :data="treeData"
        :current-node-key="defaultNodeKey"
        node-key="name"
        draggable
        highlight-current
        default-expand-all
        @node-drag-start="handleDragStart"
        @node-drag-enter="handleDragEnter"
        @node-drag-leave="handleDragLeave"
        @node-drag-over="handleDragOver"
        @node-drag-end="handleDragEnd"
        @node-drop="handleDrop"
        @current-change="handleCheckChanged"
        :allow-drop="allowDrop"
        :allow-drag="allowDrag"
      >
        <template slot-scope="{ node, data }">
          <div>
            <i v-if="data.name == defaultNodeKey" class="el-icon-success" :style="preIconStyleCur"></i>
            <i v-else-if="data.isPage" class="el-icon-document" :style="preIconStyle"></i>
            <i v-else-if="data.meta.icon" :class="data.meta.icon" :style="preIconStyle"></i>
            <span>{{ data.meta.title }}</span>
          </div>
        </template>
      </el-tree>
    </div>

    <div class="bottom-btns">
      <span style="font-size: 12px; color: red">"其他功能"为系统默认节点，无法修改、移动</span>
      <x2-space></x2-space>
      <el-button @click="handleSubmit" type="primary">保存调整</el-button>
      <el-button @click="handleCancel" type="warning">关闭返回</el-button>
    </div>
  </div>
</template>

<script>
import { isEqual } from 'lodash'
export default {
  name: 'PathSelect',
  props: ['id'],
  data() {
    return {
      isAdding: false,
      nameOfNewNode: '',
      defaultNodeKey: this.id,
      currentNode: null,
      preIconStyle: 'color:#409EFF;margin-right:6px;',
      preIconStyleCur: 'color:#67C23A;margin-right:6px;',
      isNewRecord: false,
      treeData: [],
      initData: [],
    }
  },

  mounted() {
    this.init()
  },
  methods: {
    handleAddNodeBtn() {
      if (!this.isAdding) return (this.isAdding = true)
      const id = this.$uuid()
      this.treeData.unshift({
        path: `/${id}`,
        component: '',
        redirect: null,
        name: id,
        label: this.nameOfNewNode,
        meta: {
          title: this.nameOfNewNode,
          icon: 'el-icon-s-promotion',
        },
        children: [],
      })
      this.nameOfNewNode = ''
      this.isAdding = false
    },
    async init() {
      const res = await this.$request({
        url: '/lowcode/getDataBySql',
        method: 'post',
        data: { sqlid: '文档内容', where: `dkey='appMenuList'` },
      })
      this.treeData = JSON.parse(res.list[0]['dvalue'])
      this.initData = JSON.parse(res.list[0]['dvalue'])
      this.$nextTick(() => {
        this.currentNode = this.$refs.TR.getCurrentNode()
      })
    },
    async handleCancel() {
      if (isEqual(this.initData, this.treeData)) {
        this.$emit('close')
      } else {
        try {
          const res = await this.$confirm('菜单已调整，确定放弃本次修改吗？')
          this.$emit('close')
        } catch (e) {
          console.log(e)
        }
      }
    },
    async handleSubmit() {
      const param = {
        dkey: 'appMenuList',
        dvalue: JSON.stringify(this.treeData),
      }

      const data = [
        {
          tableName: 'z_doc',
          action: 'update',
          dataList: [param],
        },
      ]
      const updateRes = await this.$request({
        url: '/lowcode/commonUpdate',
        method: 'post',
        data,
      })
      this.$emit('confirm', '')
    },

    handleCheckChanged(item, x, y) {
      console.log('item', item)
      this.currentNode = item
    },
    handleDragStart(node, ev) {
      // console.log('drag start', node)
    },
    handleDragEnter(draggingNode, dropNode, ev) {
      // console.log('tree drag enter: ', dropNode.label)
    },
    handleDragLeave(draggingNode, dropNode, ev) {
      // console.log('tree drag leave: ', dropNode.label)
    },
    handleDragOver(draggingNode, dropNode, ev) {
      // console.log('tree drag over: ', dropNode.label)
    },
    handleDragEnd(draggingNode, dropNode, dropType, ev) {
      // console.log('tree drag end: ', dropNode && dropNode.label, dropType)
    },
    handleDrop(draggingNode, dropNode, dropType, ev) {
      // console.log('tree drop: ', dropNode.label, dropType)
    },

    allowDrop(draggingNode, dropNode, type) {
      const {
        isPage: dropIsPage,
        meta: { title: dropTitle },
      } = dropNode.data

      const {
        isPage: dragIsPage,
        meta: { title: dragTitle },
      } = draggingNode.data

      // 不允许拖动到页面节点的下一级
      if (dropIsPage && type == 'inner') return false

      // 不允许页面节点拖动到根节点
      if (!dropNode.parent.parent && dragIsPage && type != 'inner') return false

      // 不允许拖动到"其他功能"下一级，让其他功能保持在最后一个分类
      if (dropTitle == '其他功能' && type == 'next') return false

      // console.log(draggingNode.data.meta.title, dropNode.data.meta.title, type)
      return true
    },
    allowDrag(draggingNode) {
      return draggingNode.data.meta.title != '其他功能'
    },
  },
}
</script>
<style scoped>
.bottom-btns {
  display: flex;
  align-items: center;
}
.tree-wrap {
  height: 600px;
  overflow: auto;
  margin-bottom: 12px;
  border: 1px solid #bbb;
}
.custom-btn {
  padding-top: 2px;
  padding-left: 2px;
  padding-right: 2px;
  padding-bottom: 2px;
}
.tree-before-wrap {
  padding: 4px 0;
  display: flex;
  align-items: center;
}
</style>
